/**
 * 轻量事件跟踪工具
 * - 本地持久化：将事件记录缓存到storage，便于后续上报或调试
 * - 非侵入设计：后端未提供接口时，仅记录本地与控制台日志
 */

const STORAGE_KEY = 'user_action_logs'

export function trackEvent(eventName, details = {}) {
  try {
    const now = Date.now()
    const record = {
      event: eventName,
      timestamp: now,
      isoTime: new Date(now).toISOString(),
      details: sanitize(details)
    }

    // 追加到本地日志
    const logs = uni.getStorageSync(STORAGE_KEY) || []
    logs.push(record)
    // 控制最大长度，避免存储膨胀
    if (logs.length > 500) {
      logs.splice(0, logs.length - 500)
    }
    uni.setStorageSync(STORAGE_KEY, logs)

    // 控制台输出，便于调试
    console.log('[EventTracker]', record)
  } catch (e) {
    console.warn('trackEvent failed:', e)
  }
}

function sanitize(obj) {
  try {
    // 仅保留可序列化的简单数据
    return JSON.parse(JSON.stringify(obj || {}))
  } catch (e) {
    return { raw: String(obj) }
  }
}

export default { trackEvent }

